<?php
namespace app\common\controller;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use think\Controller;
use app\common\model\Sms as SmsM;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use think\Db;

/**
 * 阿里云短信发送控制器
 * @package app\common\controller
 */
class Alisms extends Controller
{

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Dysmsapi Client
     */
    public static function createClient($accessKeyId, $accessKeySecret){
        $config = new Config([
            // 您的AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 您的AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /*
     * 发送短信
     * phone 手机号码
     * content  短信内容
     * flag 短信类型 1：注册账号 2:找回密码 3：短信验证 4：短信提醒 5 通知类
     * code 验证码
     * storeId 门店ID
     */
    public static function sendsms($phone, $content, $flag, $code,$storeId)
    {
        $data['code'] = $code;
        $client = self::createClient(config('ali_key'), config('ali_key_secret'));
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $phone,
            "signName" => config('sign'),
            "templateCode" => config('code_template'),
            "templateParam" => json_encode($data)
        ]);
        // 复制代码运行请自行打印 API 的返回值
        $result = $client->sendSms($sendSmsRequest);
        $result = json_encode($result);
        $result = json_decode($result,true);
        if($result['body']['code'] == 'OK'){
            //增加记录
            $codelog = array(
                'phone' => $phone,
                'code' => $code,
                'create_time' => time(),
                'status' => '1',
                'type' => $flag,
                'content' => $content,
                'store_id'=>$storeId
            );
            $res = SmsM::insert($codelog);
            if ($res) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /*
     * 验证短信验证码是否正确
     * code 验证码
     * phone 手机号码
     * type 短信类型
     */
    public  function check_smscode($phone, $code, $type)
    {
        if ($code == 123456) {
            return ['code' => 200, 'msg' => '验证通过', 'data' => ''];
        }

        $smscode = SmsM::where('phone', $phone)->where('code', $code)->where('status', 1)
            ->where('type', $type)->order('id desc')->find();
        if ($smscode) {
            //验证码过期15分钟
            if ($smscode['create_time'] + 60 * 15 < time()) {
                $msg = ['code' => 204, 'msg' => '验证码已过期', 'data' => ''];
                return $msg;
            }
            SmsM::where('id', $smscode['id'])->update(['status' => 2]);
            $msg = ['code' => 200, 'msg' => '验证通过', 'data' => ''];
            return $msg;
        } else {
            $msg = ['code' => 204, 'msg' => '验证码错误', 'data' => ''];
            return $msg;
        }
    }


    /**
     * 会员卡充值发送短信
     * @param $rechargeLodId [会员卡充值记录ID]
     * @return bool
     */
    public static function rechargeSend($rechargeLodId){
        $rechargeData = Db::name('qt_viper_card_recharge_log')
            ->field('log.id,c.mobile,c.amount,c.give_amount,log.amount as recharge_amount,log.give_amount as recharge_give_amount,log.card_type,s.name as store_name,c.card_no,log.recharge_tempid,s.id as store_id')
            ->alias('log')
            ->leftJoin('qt_viper_card c','c.id = log.viper_card_id')
            ->leftJoin('qt_store s','c.store_id = s.id')
            ->where(['log.id'=>$rechargeLodId])
            ->find();
        //金额充值
        if($rechargeData['card_type'] == '1'){
            if($rechargeData['card_no'] == null){
                $rechargeData['card_no'] = '';
            }
            $data = [
                'storeName'=>$rechargeData['store_name'],
                'cardNumber'=>$rechargeData['card_no'],
                'amount'=>$rechargeData['recharge_amount'],
                'give_amount'=>$rechargeData['recharge_give_amount'],
                'money'=>$rechargeData['amount'],
                'giveMoney'=>$rechargeData['give_amount'],
            ];
            $client = self::createClient(config('ali_key'), config('ali_key_secret'));
            $sendSmsRequest = new SendSmsRequest([
                "phoneNumbers" => $rechargeData['mobile'],
                "signName" => config('sign'),
                "templateCode" => config('recharge_template'),
                "templateParam" => json_encode($data,JSON_UNESCAPED_UNICODE)
            ]);
            // 复制代码运行请自行打印 API 的返回值
            $result = $client->sendSms($sendSmsRequest);
            $result = json_encode($result);
            $result = json_decode($result,true);
            if($result['body']['code'] == 'OK'){
                //增加记录
                $codelog = array(
                    'phone' => $rechargeData['mobile'],
                    'code' => '会员卡充值',
                    'create_time' => time(),
                    'status' => '1',
                    'type' => '5',
                    'content' => $rechargeData['store_name'].":您的卡号:".$rechargeData['card_no'].",充值:".$rechargeData['recharge_amount']."元,获赠送:".$rechargeData['recharge_give_amount']."元,剩余:".$rechargeData['amount']."元,赠送剩余:".$rechargeData['give_amount']."元,",
                    'store_id'=>$rechargeData['store_id']
                );
                $res = SmsM::insert($codelog);
                if ($res) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }elseif ($rechargeData['card_type'] == '2'){
            $numberData = Db::name('qt_viper_number_card_template')->where(['id'=>$rechargeData['recharge_tempid']])->find();
            $project = Db::name('qt_viper_number_card_template_item')->where(['number_card_template_id'=>$numberData])->order('id desc')->find();
            //次卡充值
            $data = [
                'storeName'=>$rechargeData['store_name'],
                'cardNumber'=>$rechargeData['card_no'],
                'money'=>$rechargeData['recharge_amount'],
                'number'=>$project['number'],
                'day'=>$project['expire'],
            ];
            $client = self::createClient(config('ali_key'), config('ali_key_secret'));
            $sendSmsRequest = new SendSmsRequest([
                "phoneNumbers" => $rechargeData['mobile'],
                "signName" => config('sign'),
                "templateCode" => config('number_template'),
                "templateParam" => json_encode($data)
            ]);
            // 复制代码运行请自行打印 API 的返回值
            $result = $client->sendSms($sendSmsRequest);
            $result = json_encode($result);
            $result = json_decode($result,true);
            if($result['body']['code'] == 'OK'){
                //增加记录
                $codelog = array(
                    'phone' => $rechargeData['mobile'],
                    'code' => '会员卡次卡充值',
                    'create_time' => time(),
                    'status' => '1',
                    'type' => '5',
                    'content' => $rechargeData['store_name'].":您的卡号:".$rechargeData['card_no'].",充值:".$rechargeData['recharge_amount']."元获得项目".$project['number']."次,有效期".$project['expire']."天",
                    'store_id'=>$rechargeData['store_id']
                );
                $res = SmsM::insert($codelog);
                if ($res) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }elseif ($rechargeData['card_type'] == '3'){
            $monthData = Db::name('qt_viper_month_card_template')->where(['id'=>$rechargeData['recharge_tempid']])->find();
            //月卡充值
            $data = [
                'storeName'=>$rechargeData['store_name'],
                'cardNumber'=>$rechargeData['card_no'],
                'money'=>$rechargeData['recharge_amount'],
                'number'=>$monthData['hz'],
                'day'=>$monthData['expire'],
            ];
            $client = self::createClient(config('ali_key'), config('ali_key_secret'));
            $sendSmsRequest = new SendSmsRequest([
                "phoneNumbers" => $rechargeData['mobile'],
                "signName" => config('sign'),
                "templateCode" => config('month_template'),
                "templateParam" => json_encode($data)
            ]);
            // 复制代码运行请自行打印 API 的返回值
            $result = $client->sendSms($sendSmsRequest);
            $result = json_encode($result);
            $result = json_decode($result,true);
            if($result['body']['code'] == 'OK'){
                //增加记录
                $codelog = array(
                    'phone' => $rechargeData['mobile'],
                    'code' => '会员卡月卡充值',
                    'create_time' => time(),
                    'status' => '1',
                    'type' => '5',
                    'content' => $rechargeData['store_name'].":您的卡号:".$rechargeData['card_no'].",充值:".$rechargeData['recharge_amount']."元,项目使用次数每天使用".$monthData['hz']."次,有效期".$monthData['expire']."天",
                    'store_id'=>$rechargeData['store_id']
                );
                $res = SmsM::insert($codelog);
                if ($res) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }

    }


    /**
     * 会员卡消费发送短信
     * @param $phone [发送的手机号]
     * @param $storeName [门店名称]
     * @param $cardNumber [会员卡号]
     * @param $money [消费金额]
     * @param $giveMoney [消费赠送金额]
     * @param $balance [会员余额]
     * @param $storeId [门店ID]
     * @return bool
     */
    public static function consumptionSend($phone,$storeName,$cardNumber,$money,$giveMoney,$balance,$storeId){
        $data = [
            'storeName'=>$storeName,
            'cardNumber'=>$cardNumber,
            'money'=>$money,
            'giveMoney'=>$giveMoney,
            'balance'=>$balance,
        ];
        $client = self::createClient(config('ali_key'), config('ali_key_secret'));
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $phone,
            "signName" => config('sign'),
            "templateCode" => config('consumption_template'),
            "templateParam" => json_encode($data,JSON_UNESCAPED_UNICODE)
        ]);
        // 复制代码运行请自行打印 API 的返回值
        $result = $client->sendSms($sendSmsRequest);
        $result = json_encode($result);
        $result = json_decode($result,true);
        if($result['body']['code'] == 'OK'){
            //增加记录
            $codelog = array(
                'phone' => $phone,
                'code' => '会员卡消费',
                'create_time' => time(),
                'status' => '1',
                'type' => '5',
                'content' => $storeName.":您的卡号:".$storeName.",消费:".$money."元,赠送消费:".$giveMoney."元,余:".$balance."元,感谢您的惠顾!",
                'store_id'=>$storeId
            );
            $res = SmsM::insert($codelog);
            if ($res) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }



    /**
     * 会员卡票券发放发送短信
     * @param $phone [发送的手机号]
     * @param $storeName [门店名称]
     * @param $time [过期时间]
     * @return bool
     */
    public static function TicketSend($phone,$storeName,$time){
        $data = [
            'storeName'=>$storeName,
            'time'=>$time,
        ];
        $client = self::createClient(config('ali_key'), config('ali_key_secret'));
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $phone,
            "signName" => config('sign'),
            "templateCode" => config('coupon_template'),
            "templateParam" => json_encode($data,JSON_UNESCAPED_UNICODE)
        ]);
        // 复制代码运行请自行打印 API 的返回值
        $result = $client->sendSms($sendSmsRequest);
        $result = json_encode($result);
        $result = json_decode($result,true);
        if($result['body']['code'] == 'OK'){
            //增加记录
            $codelog = array(
                'phone' => $phone,
                'code' => '会员卡票券发送',
                'create_time' => time(),
                'status' => '1',
                'type' => '5',
                'content' => $storeName."通知您，您有一张劵，将于".$time."过期，请尽快使用！"
            );
            $res = SmsM::insert($codelog);
            if ($res) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }






    //随机短信验证码
    public static function sms_rand($length = 6)
    {
        $characters = '0123456789';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }
}